package org.handsomezhi.shortlink.admin.util.interceptor;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.handsomezhi.shortlink.admin.common.biz.user.UserContext;
import org.handsomezhi.shortlink.admin.common.biz.user.UserInfoDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

import static org.handsomezhi.shortlink.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;

@Slf4j
public class RefreshInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;



    public RefreshInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


//        String token = request.getHeader("token");
//        String username = request.getHeader("username");
//
//
//        if(StrUtil.isBlank(token) || StrUtil.isBlank(username)){
//            return true;
//        }
//
//        Object userJsonInfo = stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY + username, token);
//
//        if(userJsonInfo == null){
//            return true;
//        }
//
//        UserInfoDTO userInfoDTO = JSON.parseObject(userJsonInfo.toString(), UserInfoDTO.class);
//
//        UserContext.setUser(userInfoDTO);

        String username = request.getHeader("username");
        if (StrUtil.isNotBlank(username)) {
            String userId = request.getHeader("userId");
            String realName = request.getHeader("realName");
            UserInfoDTO userInfoDTO = new UserInfoDTO(userId, username, realName);
            UserContext.setUser(userInfoDTO);
        }
        stringRedisTemplate.expire(USER_LOGIN_KEY + username,48L, TimeUnit.HOURS);

        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }
}
